package com.lagou.config;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
@ConfigurationProperties(prefix = "jedis.config")
public class JedisConfiguration {

    /**
     * 集群节点信息
     */
    private String nodes;
    /**
     * 最大连接数
     */
    private Integer maxTotal;
    /**
     * 最大空闲连接
     */
    private Integer maxIdle;
    /**
     * 连接超时时间
     */
    private Integer connectionTimeout;
    /**
     * socket读取写入超时时间
     */
    private Integer soTimeout;
    /**
     * 最大重试次数
     */
    private Integer maxAttempts;

    @Bean
    public JedisCluster jedisCluster() {
        if (StringUtils.isEmpty(nodes)) {
            throw new IllegalArgumentException("节点配置为空");
        }

        Set<HostAndPort> set = Arrays.asList(nodes.split(",")).stream().map(s -> {
            String[] split = s.split(":");
            return new HostAndPort(split[0], Integer.valueOf(split[1]));
        }).collect(Collectors.toSet());

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxTotal(maxTotal);

        return new JedisCluster(set, connectionTimeout, soTimeout, maxAttempts, jedisPoolConfig);
    }

    public void setNodes(String nodes) {
        this.nodes = nodes;
    }

    public void setMaxTotal(Integer maxTotal) {
        this.maxTotal = maxTotal;
    }

    public void setMaxIdle(Integer maxIdle) {
        this.maxIdle = maxIdle;
    }

    public void setConnectionTimeout(Integer connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public void setSoTimeout(Integer soTimeout) {
        this.soTimeout = soTimeout;
    }

    public void setMaxAttempts(Integer maxAttempts) {
        this.maxAttempts = maxAttempts;
    }
}
